package com.lhj.es.web;

import com.lhj.es.config.EsConfig;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author linghaijin
 * @date 2021-05-14 14:45
 */
@RestController
@RequestMapping("/star")
public class StarCompletionController {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @GetMapping
    public List<String> autoComplete(String term) throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        SuggestBuilder suggestBuilder = new SuggestBuilder();
        suggestBuilder.addSuggestion("star_name_suggest", SuggestBuilders.completionSuggestion("name").size(10).prefix(term));
        searchSourceBuilder.suggest(suggestBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse res = restHighLevelClient.search(searchRequest, EsConfig.COMMON_OPTIONS);
        List<String> result = new ArrayList<>();
        res.getSuggest().getSuggestion("star_name_suggest").getEntries().forEach(entry -> {
            entry.getOptions().forEach(option -> {
                result.add(option.getText().string());
            });
        });
        return result;
    }

}
